package com.uzai.console.service.user.impl;

import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.user.app.AppUpdateIdentityDto;
import com.uzai.console.dto.user.app.AppUserQuery;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wechatuser.UpdateAgentDto;
import com.uzai.console.dto.user.wechatuser.UpdateParentDto;
import com.uzai.console.dto.user.wechatuser.UpdatePartnerDto;
import com.uzai.console.entity.AppUser;
import com.uzai.console.mapper.AppUserMapper;
import com.uzai.console.service.user.AppUserTreeInfoService;
import com.uzai.console.vo.user.app.AppUserMinMaxCreateTimeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class AppUserTreeInfoServiceImpl implements AppUserTreeInfoService {

    @Autowired
    private AppUserMapper appUserMapper;

    /**
     * 修改个人微信会员身份
     *
     * @param updateIdentityDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateIdentity(AppUpdateIdentityDto updateIdentityDto) {
        if (updateIdentityDto.getId() == null || updateIdentityDto.getIdentityNew() == null || updateIdentityDto.getUserTypeNew() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser wechatUser = appUserMapper.selectById(updateIdentityDto.getId(), updateIdentityDto.getMerId());

        if (wechatUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //会员类型没有变，则身份肯定不会变化，则不修改
        if (wechatUser.getUserType().longValue() == updateIdentityDto.getUserTypeNew().longValue()) {
            return;
        }

        Long merId = wechatUser.getMerId();
        Long id = wechatUser.getId();
        //旧身份
        int identityOld = wechatUser.getIdentity().intValue();
        //新身份
        int identityNew = updateIdentityDto.getIdentityNew().intValue();
        //新用户类型
        Long userTypeNew = updateIdentityDto.getUserTypeNew();
        //上级id
        Long parentId = Tools.getLong(wechatUser.getParentId());
        //代理id
        Long agentId = Tools.getLong(wechatUser.getAgentId());
        //合伙人id
        Long parterId = Tools.getLong(wechatUser.getPartnerId());

        //自己的买家树
        String parentInfo_wo = wechatUser.getParentInfo();
        //所有下级的买家树
        String parentInfo_son = "";
        if (parentId.longValue() != 0l) {
            parentInfo_son = Tools.getStrConnect(String.valueOf(id), "_", parentInfo_wo);
        } else {
            parentInfo_son = String.valueOf(id);
        }

        //自己代理树
        String agentInfo_wo = wechatUser.getAgentInfo();
        //所有下级的代理树
        String agentInfo_son = "";
        if (agentId.longValue() != 0l) {
            agentInfo_son = Tools.getStrConnect(String.valueOf(id), "_", agentInfo_wo);
        } else {
            agentInfo_son = String.valueOf(id);
        }

        //赋值新身份
        wechatUser.setIdentity(identityNew);
        //赋值新会员类型
        wechatUser.setUserType(userTypeNew);

        //判断旧身份类型
        if (identityOld == IdentityEnum.BUYER.getId()) { // 旧身份是买家
            //判断新身份
            if (identityNew == IdentityEnum.AGENT.getId().intValue()) { //新身份是代理

                //清空该用户自己买家信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");

                /**买家转代理-身份往上升
                 * 1: 批量将下N级所有买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
                 * 2：修改下N级买家树（从此用户开始清空）
                 * 3: 修改下级的上级和买家树（全部清空）,以及更新下N级的代理信息
                 */
                //1: 批量将下N级买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
                appUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfo_son, merId);
                //2：修改下N级买家树（从此用户开始清空）
                appUserMapper.batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                appUserMapper.batchUpdateParentInfo(parentInfo_son, "", merId, false);
                //3: 修改下级的上级和买家树（全部清空）
                AppUserQuery wechatUserQuery = new AppUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setParentId(wechatUser.getId());

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
                //查询总数
                Integer count = appUserMapper.findCount(wechatUserQuery);
                //有总数，且最小创建时间有
                if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<AppUser> wechatUserList = appUserMapper.findByList(wechatUserQuery);
                            if (wechatUserList != null && wechatUserList.size() > 0) {
                                for (AppUser wechatUser_son : wechatUserList) {
                                    wechatUser_son.setParentId(0L);   //清空上级
                                    wechatUser_son.setParentInfo(""); //清空上级树
                                    wechatUser_son.setAgentId(id);    //修改代理
                                    wechatUser_son.setAgentInfo(agentInfo_son);      //修改代理树
                                    appUserMapper.updateIdentityInfo(wechatUser_son);
                                    //4：将下N级代理和下N级代理的树更新
                                    String agentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                    String agentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getAgentInfo();
                                    //分俩次替换（避免替换留下"_"符合）
                                    appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                    appUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                }
                            }
                        }
                    }
                }
            } else if (identityNew == IdentityEnum.PARTNER.getId().intValue()) { //新身份是合伙人

                //首先清空该用户自己上级信息,代理信息、合伙人信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");
                wechatUser.setAgentId(0L);
                wechatUser.setAgentInfo("");
                wechatUser.setPartnerId(0L); //变成合伙人，清空自己的合伙人信息

                /**买家转合伙人-身份往上升
                 * 1: 批量将下N级所有买家的合伙人设置为此Id，满足条件：A:买家树包含此ID
                 * 2：修改下N级买家树（从此用户开始清空）
                 * 3: 修改下级的上级和买家树（全部清空），更新合伙人信息
                 */
                //1: 批量将下N级所有买家的合伙人设置为此Id，满足条件：A:买家树包含此ID
                appUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                //2：修改下N级买家树（从此用户开始清空）
                appUserMapper.batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                appUserMapper.batchUpdateParentInfo(parentInfo_son, "", merId, false);
                //3: 修改下级的上级和买家树（全部清空），更新合伙人信息
                AppUserQuery wechatUserQuery = new AppUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setParentId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
                //查询总数
                Integer count = appUserMapper.findCount(wechatUserQuery);
                //有总数，且最小创建时间有
                if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<AppUser> wechatUserList = appUserMapper.findByList(wechatUserQuery);
                            if (wechatUserList != null && wechatUserList.size() > 0) {
                                for (AppUser wechatUser_son : wechatUserList) {
                                    wechatUser_son.setParentId(0L);   //清空上级
                                    wechatUser_son.setParentInfo(""); //清空上级树
                                    wechatUser_son.setPartnerId(id);    //修改合伙人
                                    appUserMapper.updateIdentityInfo(wechatUser_son);
                                }
                            }
                        }
                    }
                }
            }
        } else if (identityOld == IdentityEnum.AGENT.getId()) { //旧身份是代理
            //判断新身份
            if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                /**代理转买家-身份往下降
                 *  1：修改下N级代理树(摘除此代理)
                 *  2: 修改下级代理代理信息（代理的代理）、买家信息
                 */

                //1：修改下N级代理树
                //分俩次替换（避免替换留下"_"符合）
                appUserMapper.batchUpdateAgentInfo("_" + agentInfo_son, "_" + agentInfo_wo, merId, true);
                appUserMapper.batchUpdateAgentInfo(agentInfo_son, agentInfo_wo, merId, false);

                //3: 修改下级的代理和代理树
                AppUserQuery wechatUserQuery = new AppUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setAgentId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
                //查询总数
                Integer count = appUserMapper.findCount(wechatUserQuery);
                //有总数，且最小创建时间有
                if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<AppUser> wechatUserList = appUserMapper.findByList(wechatUserQuery);
                            if (wechatUserList != null && wechatUserList.size() > 0) {
                                for (AppUser wechatUser_son : wechatUserList) {
                                    //上级为空，且身份是买家
                                    if (wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                        wechatUser_son.setParentId(id);                  //修改上级
                                        wechatUser_son.setParentInfo(parentInfo_son);    //修改上级树
                                        //将下N级上级和下N级的上级树更新
                                        String parentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String parentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getParentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                    }
                                    wechatUser_son.setAgentId(agentId);           //修改新的上级代理（代理的代理）
                                    wechatUser_son.setAgentInfo(agentInfo_wo);    //修改新的代理树（代理的代理）
                                    appUserMapper.updateIdentityInfo(wechatUser_son);
                                }
                            }
                        }
                    }
                }
            } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                //首先清空该用户自己上级信息,代理信息、合伙人信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");
                wechatUser.setAgentId(0L);
                wechatUser.setAgentInfo("");
                wechatUser.setPartnerId(0L); //变成合伙人，清空自己的合伙人信息

                /**代理转合伙人-身份往上升
                 *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:代理树包含此ID，B：上级id为空；C：身份是买家
                 *  2：修改下N级代理树
                 *  3: 修改下级的代理和代理树
                 */

                //1: 批量将下N级所有的代理，将合伙人设置为此Id，满足条件：A:代理树包含此ID
                appUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);

                //2：修改下N级代理树(清空截断）
                //分俩次替换（避免替换留下"_"符合）
                appUserMapper.batchUpdateAgentInfo("_" + agentInfo_son, "", merId, true);
                appUserMapper.batchUpdateAgentInfo(agentInfo_son, "", merId, false);
                //3: 修改下级的代理和代理树
                AppUserQuery wechatUserQuery = new AppUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setAgentId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
                //查询总数
                Integer count = appUserMapper.findCount(wechatUserQuery);
                //有总数，且最小创建时间有
                if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<AppUser> wechatUserList = appUserMapper.findByList(wechatUserQuery);
                            if (wechatUserList != null && wechatUserList.size() > 0) {
                                for (AppUser wechatUser_son : wechatUserList) {
                                    wechatUser_son.setAgentId(0L);                    //清空代理人
                                    wechatUser_son.setAgentInfo("");                  //清空代理人信息
                                    wechatUser_son.setPartnerId(id);                  //修改合伙人
                                    appUserMapper.updateIdentityInfo(wechatUser_son);
                                }
                            }
                        }
                    }
                }
            }
        } else { //旧身份是合伙人
            //判断新身份
            if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                /**合伙人转买家-身份往下降
                 *  1：清空下N合伙人信息,更新买家信息（上级不能为空，代理不能为空，且身份是买家）
                 */

                //1：清空下N合伙人信息,更新买家信息
                AppUserQuery wechatUserQuery = new AppUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setPartnerId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
                //查询总数
                Integer count = appUserMapper.findCount(wechatUserQuery);
                //有总数，且最小创建时间有
                if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<AppUser> wechatUserList = appUserMapper.findByList(wechatUserQuery);
                            if (wechatUserList != null && wechatUserList.size() > 0) {
                                for (AppUser wechatUser_son : wechatUserList) {
                                    wechatUser_son.setPartnerId(0L);   // 清空合伙人
                                    //上级不能为空，代理不能为空，且身份是买家
                                    if (wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getAgentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                        wechatUser_son.setParentId(id);                   //修改上级
                                        wechatUser_son.setParentInfo(parentInfo_son);    //修改上级树

                                        //将下N级上级和下N级的上级树更新
                                        String parentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String parentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getParentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                    }
                                    appUserMapper.updateIdentityInfo(wechatUser_son);
                                }
                            }
                        }
                    }
                }
            } else if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                //首先清空该用户自己上级信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");

                /**合伙人转代理-身份往下降
                 *  1：清空下N合伙人信息,更新买家信息
                 */

                //2：清空下N合伙人信息,更新买家信息
                AppUserQuery wechatUserQuery = new AppUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setPartnerId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
                //查询总数
                Integer count = appUserMapper.findCount(wechatUserQuery);
                //有总数，且最小创建时间有
                if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<AppUser> wechatUserList = appUserMapper.findByList(wechatUserQuery);
                            if (wechatUserList != null && wechatUserList.size() > 0) {
                                for (AppUser wechatUser_son : wechatUserList) {
                                    wechatUser_son.setPartnerId(0L);  // 清空合伙人
                                    //上级不能为空，代理不能为空，且身份是代理
                                    if (wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getAgentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()) {
                                        wechatUser_son.setAgentId(id);                   //修改代理
                                        wechatUser_son.setAgentInfo(agentInfo_son);     //修改代理树

                                        //将下N级代理和下N级的代理树更新
                                        String agentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String agentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        appUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    }
                                    appUserMapper.updateIdentityInfo(wechatUser_son);
                                }
                            }
                        }
                    }
                }
            }
        }
        //更新会员信息
        appUserMapper.updateIdentityInfo(wechatUser);

    }

    /**
     * 修改上级买家-处理树
     *
     * @param updateParentDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateParent(UpdateParentDto updateParentDto) {
        if (updateParentDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(updateParentDto.getId(), updateParentDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = appUser.getMerId();
        //旧上级买家id
        long parentIdOld = Tools.getLong(appUser.getParentId()).longValue();
        //新上级买家
        long parentIdNew = Tools.getLong(updateParentDto.getParentId()).longValue();

        if (parentIdNew != parentIdOld) {//修改了上级买家
            //自己旧的买家树
            String parentInfoOld_wo = Tools.getStr(appUser.getParentInfo());

            //所有下级的旧的上级买家树
            String parentInfoOld_son = null;
            if (parentIdOld != 0) {
                parentInfoOld_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", parentInfoOld_wo);
            } else {
                parentInfoOld_son = String.valueOf(appUser.getId());
            }
            //自己新的买家树
            String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
            //所有下级的新的买家树
            String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的

            //验证上级买家
            if (parentIdNew != 0) { //选择了上级买家
                AppUser appUserParent_new = appUserMapper.selectById(parentIdNew, updateParentDto.getMerId());

                //判断存不存在
                if (appUserParent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }

                //判断身份
                if (appUserParent_new.getIdentity() == null || appUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if (appUserParent_new.getId().longValue() == appUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(appUserParent_new.getParentInfo());
                if (parentInfo.contains(String.valueOf(appUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }

                //判断新上级买家是否有上级买家，
                if (Tools.getLong(appUserParent_new.getParentId()).longValue() != 0) {//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(appUserParent_new.getId()), "_", appUserParent_new.getParentInfo());
                    appUser.setParentInfo(parentInfoNew_wo);
                } else {
                    parentInfoNew_wo = String.valueOf(appUserParent_new.getId());
                    appUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", parentInfoNew_wo);

            } else { //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                appUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(appUser.getId());
            }

            //分俩次替换（避免替换留下"_"符合）
            appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            appUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);

            //修改上级id
            appUser.setParentId(parentIdNew);
            //保存用户
            appUserMapper.updateById(appUser);
        }
    }

    /**
     * 修改代理-处理树
     *
     * @param updateAgentDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateAgent(UpdateAgentDto updateAgentDto) {
        if (updateAgentDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(updateAgentDto.getId(), updateAgentDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = appUser.getMerId();

        //旧代理
        long agentIdOld = Tools.getLong(appUser.getAgentId()).longValue();
        //新代理
        long agentIdNew = Tools.getLong(updateAgentDto.getAgentId()).longValue();

        if (agentIdNew != agentIdOld) { //表示修改了上级代理

            //自己旧的代理树
            String agentInfoOld_wo = Tools.getStr(appUser.getAgentInfo());

            //所有下级旧的代理树
            String agentInfoOld_son = null;
            if (agentIdOld != 0) {
                agentInfoOld_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", agentInfoOld_wo);
            } else {
                agentInfoOld_son = String.valueOf(appUser.getId());
            }
            //自己新的代理树
            String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
            //所有下级新的代理树
            String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的

            if (agentIdNew != 0) { //选择了上级代理，需要验证身份
                AppUser appUserAgent_new = appUserMapper.selectById(agentIdNew, updateAgentDto.getMerId());
                //判断存不存在
                if (appUserAgent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if (appUserAgent_new.getIdentity() == null || appUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if (appUserAgent_new.getId().longValue() == appUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(appUserAgent_new.getAgentInfo());
                if (agentInfo.contains(String.valueOf(appUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if (Tools.getLong(appUserAgent_new.getAgentId()) != 0) { //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(appUserAgent_new.getId()), "_", appUserAgent_new.getAgentInfo());
                    appUser.setAgentInfo(agentInfoNew_wo);
                } else {
                    agentInfoNew_wo = String.valueOf(appUserAgent_new.getId());
                    appUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", agentInfoNew_wo);
            } else { //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                appUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(appUser.getId());
            }

            //分俩次替换（避免替换留下"_"符合）
            appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            appUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);

            //修改代理id
            appUser.setAgentId(agentIdNew);
            //保存会员
            appUserMapper.updateById(appUser);
        }
    }

    /**
     * 修改合伙人
     *
     * @param updatePartnerDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updatePartner(UpdatePartnerDto updatePartnerDto) {
        if (updatePartnerDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(updatePartnerDto.getId(), updatePartnerDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = appUser.getMerId();

        //旧合伙人
        long partnerIdOld = Tools.getLong(appUser.getPartnerId()).longValue();
        //新合伙人
        long partnerIdNew = Tools.getLong(updatePartnerDto.getPartnerId()).longValue();

        if (partnerIdOld != partnerIdNew) { //表示修改了合伙人
            //选择了合伙人，验证对方身份
            if (partnerIdNew != 0) {
                AppUser appUserPartner_new = appUserMapper.selectById(partnerIdNew, updatePartnerDto.getMerId());
                //判断存不存在
                if (appUserPartner_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if (appUserPartner_new.getIdentity() == null || appUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if (appUserPartner_new.getId().longValue() == appUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
            }

            //修改自己的合伙人id
            appUser.setPartnerId(partnerIdNew);
            //保存会员
            appUserMapper.updateById(appUser);
        }
    }


    /**
     * 删除上级代理
     *
     * @param wechatUser_son
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deletePartner(WechatUser wechatUser_son) {

    }
}
